import socket
import time
from machine import Pin
import gc

class WebServer:
    """简单的Web服务器，用于DNS管理界面"""
    
    def __init__(self, port=80):
        self.port = port
        self.socket = None
        self.running = False
        
    def start(self):
        """启动Web服务器"""
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.bind(('0.0.0.0', self.port))
            self.socket.listen(5)
            
            self.running = True
            print(f"[web]Web服务器正在监听端口 {self.port}")
            
            while self.running:
                try:
                    client, addr = self.socket.accept()
                    self.handle_client(client, addr)
                except Exception as e:
                    print(f"[web]Web服务器错误: {e}")
                    continue
                    
        except Exception as e:
            print(f"[web]启动Web服务器失败: {e}")
        finally:
            self.stop()
    
    def stop(self):
        """停止Web服务器"""
        self.running = False
        if self.socket:
            self.socket.close()
            self.socket = None
        print("[web]Web服务器已停止")
    
    def handle_client(self, client, addr):
        """处理客户端连接"""
        try:
            request = client.recv(1024).decode('utf-8')
            if request:
                response = self.generate_response()
                client.send(response.encode('utf-8'))
        except Exception as e:
            print(f"[web]处理客户端请求失败: {e}")
        finally:
            client.close()
    
    def generate_response(self):
        """生成HTTP响应"""
        html = """<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>ESP32 DNS服务器</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f0f0f0; }
        .container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h1 { color: #333; text-align: center; }
        .status { background: #e8f5e8; padding: 15px; border-radius: 5px; margin: 20px 0; }
        .info { background: #e3f2fd; padding: 15px; border-radius: 5px; margin: 20px 0; }
    </style>
</head>
<body>
    <div class="container">
        <h1>ESP32 DNS服务器</h1>
        
        <div class="status">
            <h2>服务器状态</h2>
            <p><strong>状态:</strong> 运行中</p>
            <p><strong>IP地址:</strong> 192.168.4.1</p>
            <p><strong>DNS端口:</strong> 53</p>
            <p><strong>Web端口:</strong> 80</p>
        </div>
        
        <div class="info">
            <h2>连接信息</h2>
            <p><strong>WiFi SSID:</strong> ESP32_DNS_Server</p>
            <p><strong>WiFi密码:</strong> 12345678</p>
            <p><strong>DNS服务器地址:</strong> 192.168.4.1</p>
            <p><a href="http://www.baidu.com" target="_blank">访问百度</a></p>
        </div>
        
        <div class="info">
            <h2>使用说明</h2>
            <ol>
                <li>连接到ESP32_DNS_Server WiFi网络</li>
                <li>设置DNS服务器地址为192.168.4.1</li>
                <li>所有域名查询将被解析到ESP32的IP地址</li>
            </ol>
        </div>
        <div class="info">
            <h2>测试链接</h2>
            <p>百度</p>
        </div>
    </div>
</body>
</html>"""
        
        return f"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {len(html)}\r\n\r\n{html}" 